public class Interview0406 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    boolean isFind;

    TreeNode nextNode;

    private void dfs(TreeNode tmpNode, TreeNode targetNode){
        if(tmpNode == null || nextNode != null){
            return;
        }
        dfs(tmpNode.left, targetNode);
        if(isFind && nextNode == null){
            nextNode = tmpNode;
        }
        if(tmpNode == targetNode){
            isFind = true;
        }
        dfs(tmpNode.right, targetNode);
    }

    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        isFind = false;
        nextNode = null;
        dfs(root, p);
        return nextNode;
    }

}
